import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {Button, Input, Picker, Text, View} from '@tarojs/components'
import {AtIcon, AtModal, AtModalAction, AtModalContent, AtModalHeader, AtTextarea} from "taro-ui";
import {
  TEAM_APPOINT_RECEIVE,
  TEAM_APPOINT_REJECT, TEAM_APPOINT_PAGE, IDENTITY
} from '../../../constants/api'
import {newHttp} from "../../../utils/request";
import {http} from "../../../utils/http";
import {UserIdentity} from "../../../utils/server.interface";
import {user} from "../../../utils/user.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../../utils/tools";
import './splist.scss'

interface StateType {
  show: boolean
  isRefuseOpen: boolean
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  tabIndex: number
  queryData: {
    supplier_id: string
    reserveDateEnd: string
    order_num: string
    reserveDate: string
    reserveStatus: string
    link_phone: string
    link_name: string
    goods_name: string
    pageSize: number
    pageNumber: number
  }
  refuseData: object
  tabData: any
  supplierIndex: number
  supplierChecked: string
  inputText: string
  listData: any
  supplierList: any
  isFirst: boolean
}

export default class ManageAppointment extends Component {
  state: StateType = {
    loadMoreStatus: 'loading',
    tabData: [{title: '全部', index: 0, value: ''}, {title: '已接收', index: 1, value: '1'}, {
      title: '已拒绝',
      index: 2,
      value: '2'
    }, {title: '已完成', index: 3, value: '3'}],
    queryData: {
      type: 'supplier',
      supplier_id: '',
      search_status: '',
      pageSize: 10,
      pageNumber: 1
    },
    tabIndex: 0,
    supplierChecked: '',
    supplierIndex: 0,
    show: false,
    isRefuseOpen: false,
    refuseData: {
      order_num: '',
      order_id: '',
      supplier_id: '',
      cause: ''
    },
    inputText: '',
    listData: [],
    supplierList: [],
    isFirst: true
  }
  page = 1

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity: any = await http.get<UserIdentity>(IDENTITY, {})
      if (userIdentity && userIdentity.isSupplier) {
        let supplierChecked = ''
        let supplierIndex = Taro.getStorageSync('mySupplierIndex') || 0
        if (userIdentity.SupplierList.length > 0) {
          supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
          supplierChecked = userIdentity.SupplierList[supplierIndex].company
          this.state.queryData.supplier_id = userIdentity.SupplierList[supplierIndex].supplier_id
          Taro.setStorageSync('mySupplierIndex', supplierIndex)
        }
        this.setState({supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex})
      } else {
        Taro.showToast({
          title: '您还没有供应商，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
    this.getListData(this.state.queryData)
  }

  async onPullDownRefresh() {
    Taro.showNavigationBarLoading()
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = this.page
    const data = await newHttp.get(TEAM_APPOINT_PAGE, this.state.queryData)
    data.data.map(async (item) => {
      if (item.info_item_detail_config) item.info_item_detail_config = JSON.parse(item.info_item_detail_config)
    })
    this.setState({queryData, listData: data.data})
    Taro.hideNavigationBarLoading()
    Taro.stopPullDownRefresh()
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const {queryData} = this.state
      this.page++
      queryData['pageNumber'] = this.page
      const old = this.state.listData
      const data = await newHttp.get(TEAM_APPOINT_PAGE, queryData)
      data.data.map(async (item) => {
        if (item.info_item_detail_config) item.info_item_detail_config = JSON.parse(item.info_item_detail_config)
      })
      if (data.data.length < queryData.pageSize) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: [...old, ...data.data]})
    }
  }

  async getListData(queryData) {
    Taro.showLoading({title: '加载中'})
    const data = await newHttp.get(TEAM_APPOINT_PAGE, queryData)
    data.data.map(async (item) => {
      if (item.info_item_detail_config) item.info_item_detail_config = JSON.parse(item.info_item_detail_config)
    })
    if (data.data.length < queryData.pageSize) {
      this.setState({loadMoreStatus: 'noMore'})
    } else {
      this.setState({loadMoreStatus: 'more'})
    }
    this.setState({queryData, listData: data.data})
    Taro.hideLoading()
  }

  handlerTab(tabIndex, reserveStatus) {
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = this.page
    queryData['search_status'] = reserveStatus
    this.setState({tabIndex, queryData})
    this.getListData(queryData)
  }

  handleChange(field, val) {
    if (typeof val === 'object') {
      val = val.detail.value
    }
    const {queryData} = this.state
    queryData[field] = val
    this.setState({queryData})
  }

  handleForm() {
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = 1
    this.getListData(queryData)
  }

  onChange(e) {
    const {supplierList, queryData} = this.state
    this.page = 1
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    queryData['pageNumber'] = 1
    queryData['supplier_id'] = supplierList[supplierIndex].supplier_id
    this.setState({supplierIndex, supplierChecked})
    Taro.setStorageSync('mySupplierIndex', supplierIndex)
    this.getListData(queryData)
  }

  refuseHandleChange(val) {
    const {refuseData} = this.state
    refuseData['cause'] = val
    this.setState({refuseData})
  }

  async confirmRefuse() {
    const {refuseData} = this.state
    await http.post(TEAM_APPOINT_REJECT, refuseData)
    const {queryData} = this.state
    this.page = 1
    queryData['pageNumber'] = 1
    this.getListData(queryData)
    Taro.showToast({title: '拒绝成功', icon: 'none'})
    this.setState({isRefuseOpen: false})
  }

  async doDeal(goodsId, orderNum) {
    await newHttp.post(TEAM_APPOINT_RECEIVE, {goodsId, orderNum, type: 0})
    Taro.showToast({title: '接收成功', icon: 'none'})
    const {queryData} = this.state
    this.getListData(queryData)
  }

  doRefuse(goodsId, orderNum) {
    const refuseData = {goodsId, orderNum, cause: '', supplier_id: this.state.queryData.supplier_id, type: 0}
    this.setState({isRefuseOpen: true, refuseData})
  }

  inputChange(e) {
    const {queryData} = this.state
    queryData['search_supplier'] = e.detail.value
    this.setState({queryData})
  }

  jump(url) {
    Taro.navigateTo({
      url
    })
  }

  render() {
    const {
      tabData,
      isRefuseOpen,
      refuseData,
      supplierList,
      supplierChecked,
      supplierIndex,
      listData,
      tabIndex,
      show,
      queryData,
      loadMoreStatus
    } = this.state
    return (
      <View className='root yuyue-root'>
        <GzhAuth />
        <View className='header-top' style={`background-color: ${process.env.mainColor}`}>
          <View className='head-picker'>
            {supplierList.length >= 1 &&
              <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
                <View className={supplierChecked ? 'picker' : 'picker off'}>
                  {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                  <Text>切换</Text>
                </View>
              </Picker>}
          </View>
          <View className='input-box'>
            <View className='input input-i-cla'>
              <Input placeholderClass='input_pla' placeholder='订单号/产品名称/领队名称/领队电话'
                onInput={this.inputChange.bind(this)}
              />
            </View>
            <View className='btn' onClick={this.handleForm.bind(this)}><AtIcon prefixClass='xxhz' value='sousuo2'
              size='18' color='#fff'
            /></View>
          </View>
        </View>
        <View className='tab-header'>
          {tabData && tabData.map((item, index) =>
            <View key={index} className={`tab-item ${tabIndex === item.index ? 'tab-item-active' : ''}`}
              onClick={this.handlerTab.bind(this, item.index, item.value)}
            >
              <View className='line-title'>
                {item.title}
              </View>
              <View className={`at-tabs_item_underline ${tabIndex === item.index ? 'underline-active' : ''}`} />
            </View>
          )}
        </View>
        {listData && listData.length > 0 &&
          <View className='article-body'>
            {listData.map((item, index) =>
              <View className='article-item' key={index}>
                <View className='article-body-header'>
                  <View className='header-left'>{item.goods_name}</View>
                  <View className='header-right'>
                    {item.status === 0 && <Text>待接收</Text>}
                    {item.status === 1 && <Text>已接收</Text>}
                    {item.status === 2 && <Text>已拒绝</Text>}
                    {item.status === 3 && <Text>已完成</Text>}
                  </View>
                </View>
                <View className='line' />
                <View className='goods-item'>订单号：{item.order_num}</View>
                {item.info_item_detail_config.reserve_date &&
                  <View className='goods-item'>预约时间：{item.reserve_date}</View>}
                {item.info_item_detail_config.in_date && <View className='goods-item'>入场时间：{item.inDate}</View>}
                {item.info_item_detail_config.team_org && <View className='goods-item'>组团单位：{item.team_org}</View>}
                {item.info_item_detail_config.linkman && <View className='goods-item'>领队姓名：{item.linkman}</View>}
                {item.info_item_detail_config.link_phone &&
                  <View className='goods-item'>领队电话：{item.link_phone}</View>}
                {item.info_item_detail_config.team_address &&
                  <View className='goods-item'>客源地：{item.team_address}</View>}
                {item.info_item_detail_config.guide_num &&
                  <View className='goods-item'>讲解员人数：{item.guide_num}</View>}
                {item.info_item_detail_config.is_reserve_meal &&
                  <View className='goods-item'>是否订餐：{!!item.is_reserve_meal ? '是' : '否'}</View>}
                {item.info_item_detail_config.custom_num &&
                  <View className='goods-item'>预约人数：{item.custom_num}</View>}
                {item.status === 3 && <View className='goods-item'>实际人数：{item.real_custom_num}</View>}
                <View className='btnGroup'>
                  {item.status === 0 && !item.third_supplier_order_num &&
                    <View className='arrangement' onClick={this.doDeal.bind(this, item.goods_id, item.order_num)}>
                      <View className='arrangement-btn'>接收</View>
                    </View>}
                  {item.status === 0 && !item.third_supplier_order_num &&
                    <View className='arrangement' onClick={this.doRefuse.bind(this, item.goods_id, item.order_num)}>
                      <View className='arrangement-btn'>拒绝</View>
                    </View>}
                  <View className='arrangement'
                    onClick={this.jump.bind(this, '/page/my/teamappoint/order/detail?orderNum=' + item.order_num + '&orderId=' + item.id + `&page=supplier&supplierId=${queryData.supplier_id}`)}
                  >
                    <View className='arrangement-btn'>详情</View>
                  </View>
                </View>
              </View>
            )}
          </View>}
        {listData.length <= 0 && <View className='no-data' style='font-size: 16px;'>您还没有团队预约信息</View>}
        {isRefuseOpen && <AtModal className='model' isOpened={isRefuseOpen}>
          <AtModalHeader>拒绝原因<AtIcon onClick={() => {
            this.setState({isRefuseOpen: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <AtModalContent>
            <View className={`${refuseData.cause == '' ? 'mepty' : 'black'}`}>
              <AtTextarea
                count={false}
                value={refuseData.cause}
                onChange={this.refuseHandleChange.bind(this)}
                maxLength={200}
                placeholder='请输入拒绝原因'
                placeholderStyle='color: #c5c5c5;'
              />
            </View>
          </AtModalContent>
          <AtModalAction><Button className='readed' onClick={this.confirmRefuse.bind(this)}>确定</Button>
          </AtModalAction>
        </AtModal>}
      </View>
    )
  }
}
